# -*- coding: utf-8 -*-

import os
import xlwt
import time
from lib.logger import logger
import json
import sys, argparse

if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')


def read_txt(dir="/tmp/get_system_info/"):
    """
    遍历读取目录下的母舰
    :param dir: 目录 /tmp/
    :return:
    """
    datalist = []

    def get_path_file(path):
        """
        获取目录下的所有文件
        :param path:
        :return:
        """
        for file in os.listdir(path):
            file_path = path + "/" + file

            if os.path.isdir(file_path):
                get_path_file(file_path)
            else:

                logger.info(u"Start read files:{}".format(file_path))

                with open(file_path, "r") as f:
                    for line in f.readlines():
                        line = line.split(";")[0:-1]
                        datalist.append(line)

    get_path_file(dir)
    return datalist


def creat_excel(task_name, save_path, cloumns, data):
    """
    生成excel文件
    :param task_name: 任务名
    :return:
    """
    today = time.strftime("%Y_%m_%d_%H_%M", time.localtime())
    excel_name = "{}/{}_{}.xls".format(save_path, task_name, today)
    # 自动创建路径
    if os.path.exists(save_path) is False:
        os.makedirs(save_path)

    logger.info(u"Start create report:{}".format(excel_name))

    report = xlwt.Workbook(encoding='utf-8')
    sheet = report.add_sheet(task_name)

    # 创建表头和列宽
    for x, cloumn in enumerate(cloumns):
        sheet.write(0, x, cloumn["title"])
        sheet.col(x).width = 256 * cloumn["width"]

    # 写入数据
    for x, row in enumerate(data):
        x = x + 1
        for y, data in enumerate(row):
            sheet.write(x, y, data)

    report.save(excel_name)

    logger.info(u"Create report end:{}".format(excel_name))


if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="自动化巡检")
    # 设置可能的命令行参数来运行程序
    parser.add_argument('--task', dest='task_name', required=True,help = "任务名，配置文件在conf/config.json")

    args = parser.parse_args()
    task_name = args.task_name

    if task_name == None:
        logger.info(u"Must required --task 例如：./run --task taskname ")
        exit()

    with open("conf/config.json", "r") as f:
        config = json.loads(f.read())
        for task in config["tasks"]:
            if task_name == task["task_name"]:
                data = read_txt(task["data_path"])
                task_name = task["task_name"]
                save_path = task["save_path"]
                cloumns = task["cloumns"]

                logger.info(u"{} Task start...".format(task_name))

                creat_excel(task_name, save_path, cloumns, data)

                logger.info(u"{} Task end...".format(task_name))
